package com.flc.gateway.server;

import com.flc.gateway.config.AppConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author haizi
 * @date 2017/12/31
 */
public class Server {

    private static final Logger logger = LoggerFactory.getLogger(Server.class);

    private int port;

    private int backlog;

    private Boolean keepalive;

    private int heartBeat;

    public Server(AppConfig.NettyCfg nettyCfg) {
        port = nettyCfg.getPort();
        backlog = nettyCfg.getBacklog();
        keepalive = nettyCfg.getKeepalive();
        heartBeat = nettyCfg.getHeartBeat();
    }

    public void run() throws Exception {

        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                     .channel(NioServerSocketChannel.class)
                     .option(ChannelOption.SO_BACKLOG, backlog)
                     .childOption(ChannelOption.SO_KEEPALIVE, keepalive)
                     .childHandler(new ServerInitializer(heartBeat));

            //绑定端口
            ChannelFuture future = bootstrap.bind(port).sync();

            if(future.isSuccess()) {
                logger.info("服务器已经开启了，端口：" + port);
            }

            future.channel().closeFuture().sync();

        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
